

<script setup lang="ts">
import { postMemberAddressAPI } from '@/services/address';
import type { AddressParams } from '@/types/address';
import { ref } from 'vue';

const query = defineProps<{
  id?:string
}>()

const form = ref({
  receiver: '', // 收货人
  contact: '', // 联系方式
  fullLocation: '', // 省市区(前端展示)
  provinceCode: '', // 省份编码(后端参数)
  cityCode: '', // 城市编码(后端参数)
  countyCode: '', // 区/县编码(后端参数)
  address: '', // 详细地址
  isDefault: 0, // 默认地址，1为是，0为否
})

const onRegionChange: UniHelper.RegionPickerOnChange = (ev) => {
  form.value.fullLocation = ev.detail.value.join(' ')
  const [provinceCode,cityCode,countyCode] = ev.detail.code!
  Object.assign(form.value, {provinceCode,cityCode,countyCode})
}

const onSwitchChange: UniHelper.SwiperOnChange = (ev) => {
  form.value.isDefault = ev.detail.value ? 1 : 0
}

const onSubmit = async() => {
  await postMemberAddressAPI(form.value)
  uni.showToast({icon:'success',title:'添加成功'})
  setTimeout(() => {
    uni.navigateBack()
  }, 400);
}

uni.setNavigationBarTitle( {title: query.id  ? '修改地址' : '新建地址'} )

</script>

<template>
  
  <view class="content">

    <form>
      <view class="form-item">
        <text class="label">收货人</text>
        <input class="input" placeholder="请填写收货人姓名" v-model="form.receiver"/>
      </view>
      <view class="form-item">
        <text class="label">手机号码</text>
        <input class="input" placeholder="请填写收货人手机号码" v-model="form.contact"/>
      </view>
      <view class="form-item">
        <text class="label">所在地区</text>
        <picker class="picker" mode="region" :value="form.fullLocation.split(' ')" @change="onRegionChange">
          <view v-if="form.fullLocation">{{ form.fullLocation }}</view>
          <view v-else class="placeholder">请选择省/市/区(县)</view>
        </picker>
      </view>
      <view class="form-item">
        <text class="label">详细地址</text>
        <input class="input" placeholder="街道、楼牌号等信息" v-model="form.address" />
      </view>
      <view class="form-item">
        <text class="label">设为默认地址</text>
        <switch class="switch" :checked="form.isDefault === 1" @change="onSwitchChange" />
      </view>
    </form>

  </view>

  <button class="button">保存并使用</button>

</template>

<style lang="scss">

page {
  height: 100%;
  overflow: hidden;
  background-color: #f4f4f4;
}

.content {
  margin: 20rpx;
  background-color: white;
  padding: 0 20rpx;
  border-radius: 10rpx;
}

.form-item {
  height: 80rpx;
  display: flex;
  align-items: center;
  border-bottom: 1rpx solid #f4f4f4;
  position: relative;

  &:last-child {
    border: none;
  }
}

.label {
  width: 180rpx;
  font-size: 26rpx;
  color: #333;
}

.input {
  flex: 1;
  color: #333;
  font-size: 26rpx;
}

.switch {
  position: absolute;
  right: -10rpx;
  transform: scale(0.8);
}

.placeholder {
  color: #808080;
}

.button {
  margin: 30rpx 20rpx;
  color: white;
  background-color: #27BA9B;
  font-size: 30rpx;
  border-radius: 40rpx;
  height: 80rpx;
}

</style>